
using System;
using System.Data;
using System.Linq;
using System.Linq.Dynamic;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;

using Abp.UI;
using Abp.AutoMapper;
using Abp.Extensions;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Application.Services.Dto;
using Abp.Linq.Extensions;
using JYJ.AiYard.Extension;
using JYJ.AiYard.StationManagement.TbSales;
using JYJ.AiYard.StationManagement.TbSales.Dtos;
using JYJ.AiYard.StationManagement.TbSales.DomainService;
using JYJ.AiYard.StationManagement.TbSales.Authorization;
using JYJ.AiYard.Extension;
using JYJ.AiYard.Database;
using Microsoft.AspNetCore.Http;
using JYJ.AiYard.StationManagement.YardReport;
using JYJ.AiYard.StationManagement.YardCommonHald;

namespace JYJ.AiYard.StationManagement.TbSales
{
    /// <summary>
    /// TbSale应用层服务的接口实现方法  
    ///</summary>
    [AbpAuthorize]
    public class TbSaleAppService : AiYardAppServiceBase, ITbSaleAppService
    {
        private readonly IRepository<TbSale, long> _entityRepository;

        private readonly ITbSaleManager _entityManager;

        private readonly IHttpService _httpService;

        protected IHttpContextAccessor _httpContext;

        private readonly IAiYardDbTableIssuedCard _aiYardDbTableIssuedCard;
        /// <summary>
        /// 构造函数 
        ///</summary>
        public TbSaleAppService(
        IRepository<TbSale, long> entityRepository
        ,ITbSaleManager entityManager
        ,IHttpService httpService
        ,IHttpContextAccessor httpContextAccessor
        , IAiYardDbTableIssuedCard aiYardDbTableIssuedCard
        )
        {
            _entityRepository = entityRepository; 
             _entityManager=entityManager;
            _httpService = httpService;
            _httpContext = httpContextAccessor;
            _aiYardDbTableIssuedCard = aiYardDbTableIssuedCard;
        }


        /// <summary>
        /// 获取TbSale的分页列表信息
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
		[AbpAuthorize(TbSalePermissions.Query)] 
        public async Task<PagedResultDto<TbSaleListDto>> GetPaged(GetTbSalesInput input)
		{
            List<long> StationList = new List<long>();
            tbQFilterText filterText = input.FilterText.ToObject<tbQFilterText>();
            if (filterText.StationId == null || filterText.StationId <= 0)
            {
                StationList = GetCurrenUserOrganizationAndChildrenUnit();
            }
            else
            {
                StationList.Add((long)filterText.StationId);
            }
            var query = _entityRepository.GetAll().Where(o => StationList.Contains(o.Station_ID));
            // TODO:根据传入的参数添加过滤条件
            if (!string.IsNullOrEmpty(filterText.FilterText))
                query = query.Where(o => o.Sale_Name.Contains(filterText.FilterText) || o.Sale_No.Contains(filterText.FilterText)
                || o.Sale_FullName.Contains(filterText.FilterText));

            var count = await query.CountAsync();

			var entityList = await query
					.OrderBy(input.Sorting).AsNoTracking()
					.PageBy(input)
					.ToListAsync();

			// var entityListDtos = ObjectMapper.Map<List<TbSaleListDto>>(entityList);
			var entityListDtos =entityList.MapTo<List<TbSaleListDto>>();

			return new PagedResultDto<TbSaleListDto>(count,entityListDtos);
		}


        /// <summary>
        /// 查询商户数据
        /// </summary>
        /// <returns></returns>
        public async Task<List<TbSaleListDto>> GetTbSaleList(long StationId)
        {
            var query = _entityRepository.GetAll().Where(o => o.Station_ID == StationId);
            // TODO:根据传入的参数添加过滤条件 
            var count = await query.CountAsync();

            var entityList = await query                    
                    .ToListAsync(); 
            var entityListDtos = entityList.MapTo<List<TbSaleListDto>>();

            return entityListDtos;
        }


		/// <summary>
		/// 通过指定id获取TbSaleListDto信息
		/// </summary>
		[AbpAuthorize(TbSalePermissions.Query)] 
		public async Task<TbSaleListDto> GetById(EntityDto<long> input)
		{
			var entity = await _entityRepository.GetAsync(input.Id);

		    return entity.MapTo<TbSaleListDto>();
		}

		/// <summary>
		/// 获取编辑 TbSale
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize(TbSalePermissions.Create,TbSalePermissions.Edit)]
		public async Task<GetTbSaleForEditOutput> GetForEdit(NullableIdDto<long> input)
		{
			var output = new GetTbSaleForEditOutput();
             TbSaleEditDto editDto;

			if (input.Id.HasValue)
			{
				var entity = await _entityRepository.GetAsync(input.Id.Value);

				editDto = entity.MapTo<TbSaleEditDto>(); 
			}
			else
			{
				editDto = new TbSaleEditDto();
			}

			output.TbSale = editDto;
			return output;
		}

        #region 获取商户信息
        public async Task<TbSaleListDto> GetTbSaleBySaleNo(long StationId)
        {
            long Station_Id = GetCurrenUserOrganizationUnit();
            if (StationId != 0)
            {
                Station_Id = StationId;
            } 
            var entity = await _entityRepository.GetAll().Where(o =>
                o.Station_ID == Station_Id && o.Sale_No == AbpSession.GetUserName()).ToListAsync();
            if (entity.Count > 0)
                return entity[0].MapTo<TbSaleListDto>();
            else
                return new TbSaleListDto();
        }
        #endregion

        /// <summary>
        /// 添加或者修改TbSale的公共方法
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(TbSalePermissions.Create,TbSalePermissions.Edit)]
		public async Task<Dictionary<string,string>> CreateOrUpdate(CreateOrUpdateTbSaleInput input)
		{
            if (input.TbSale.Station_ID <= 0)
            {
                throw new UserFriendlyException("请选择确定的场所名称");
            }
            if (input.TbSale.Id.HasValue)
			{
				return await Update(input.TbSale);
			}
			else
			{
				return await Create(input.TbSale);
			}
		}


        /// <summary>
        /// 新增TbSale
        /// </summary>
        [AbpAuthorize(TbSalePermissions.Create)]
        protected virtual async Task<Dictionary<string, string>> Create(TbSaleEditDto input)
        {
            Dictionary<string,string> result = new Dictionary<string, string>();
            string Sale_NoMsg = input.Sale_No;
            //当是添加时，在商户代码前加入组织NO
            input.Sale_No = _aiYardDbTableIssuedCard.GetTbObject_NO(input.Station_ID) + input.Sale_No;

            //当同一组织下如果相同的商户代码将不允许
            var query = _entityRepository.GetAll().Where(o =>
                o.Station_ID == input.Station_ID && o.Sale_No == input.Sale_No).ToList();
            if (query.Count() > 0)
            {
                result.Add("retype", "-1");
                result.Add("revalue", "已经存在【"+ Sale_NoMsg + "】商户代码");
            }
            else
            { 
                var entity = input.MapTo<TbSale>(); 
                entity = await _entityRepository.InsertAsync(entity);
                result.Add("retype", "1");
                result.Add("revalue", "保存商户成功");
            }
            return result;
            //return entity.MapTo<TbSaleEditDto>();
		}

		/// <summary>
		/// 编辑TbSale
		/// </summary>
		[AbpAuthorize(TbSalePermissions.Edit)]
		protected virtual async Task<Dictionary<string, string>> Update(TbSaleEditDto input)
		{
            Dictionary<string, string> result = new Dictionary<string, string>();
            result.Add("retype", "1");
            result.Add("revalue", "保存商户成功");
            //修改时不允许修改相同的
            var entity = await _entityRepository.GetAsync(input.Id.Value);
			input.MapTo(entity);

			// ObjectMapper.Map(input, entity);
		    await _entityRepository.UpdateAsync(entity);
            return result;
		}



		/// <summary>
		/// 删除TbSale信息的方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize(TbSalePermissions.Delete)]
		public async Task<Dictionary<string, string>> Delete(EntityDto<long> input)
		{
            Dictionary<string, string> result = new Dictionary<string, string>();
            if (_aiYardDbTableIssuedCard.CheckIsForeignKey(input.Id, 0, "Sale"))
            {
                
                result.Add("retype", "0");
                result.Add("revalue", "存在外键约束不允许删除");
                return result;

                //throw new Exception(input.Id + "存在外键约束，不允许删除");
            }
            //TODO:删除前的逻辑判断，是否允许删除
            await _entityRepository.DeleteAsync(input.Id);
            result.Add("retype", "1");
            result.Add("revalue", "删除成功");
            return result;
        }



		/// <summary>
		/// 批量删除TbSale的方法
		/// </summary>
		[AbpAuthorize(TbSalePermissions.BatchDelete)]
		public async Task<Dictionary<string, string>> BatchDelete(List<long> input)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
            foreach (long Id in input)
            {
                if (_aiYardDbTableIssuedCard.CheckIsForeignKey(Id, 0, "Sale"))
                {
                    result.Add("retype", "0");
                    result.Add("revalue", "存在外键约束不允许删除");
                    return result;
                }
            }
            // TODO:批量删除前的逻辑判断，是否允许删除
            await _entityRepository.DeleteAsync(s => input.Contains(s.Id));
            result.Add("retype", "1");
            result.Add("revalue", "删除成功");
            return result;
        }

        /// <summary>
		/// 删除TbSale信息的方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize(TbSalePermissions.Delete)]
        public async Task DeleteV2(EntityDto<long> input, bool isDelete)
        { 
            //TODO:删除前的逻辑判断，是否允许删除
            await _entityRepository.DeleteAsync(input.Id);
        }



        /// <summary>
        /// 批量删除TbSale的方法
        /// </summary>
        [AbpAuthorize(TbSalePermissions.BatchDelete)]
        public async Task BatchDeleteV2(List<long> input, bool isDelete)
        { 
            // TODO:批量删除前的逻辑判断，是否允许删除
            await _entityRepository.DeleteAsync(s => input.Contains(s.Id));
        }

        #region 获取二维码字符串
        /// <summary>
        /// 获取二维码字符串
        /// </summary>
        /// <param name="Station_ID"></param>
        /// <param name="SaleID"></param>
        /// <returns></returns>
        public string GetBarCode(int Station_ID,int SaleID)
        {
            string host = _httpContext.HttpContext.Request.Host.Host.Replace("www", "pay").Replace("aiweb", "pay").Replace("webx", "pay").Replace("web.", "minipay.").Replace("yun4.", "pay.").Replace("p.", "t.");
#if DEBUG
            host = "pay.aiyard.cn";
#endif

            string Url = (host.Contains("minipay.") ? "https://" : "http://") + host + ":1888/api/v1.0/YardLogin/GetSaleUrl?host=https%3A%2F%2F" + host + "%2F&StationId=" + Station_ID.ToString() + "&SaleId=" + SaleID.ToString() + "&timestamp=1";
            
            return _httpService.Get(Url).Replace('"', ' ').Trim();
        }
        #endregion

        #region 获取动态二维码字符串
        /// <summary>
        /// 获取二维码字符串
        /// </summary>
        /// <param name="Station_ID"></param>
        /// <param name="SaleID"></param>
        /// <returns></returns>
        public string GetDTBarCode(int Station_ID, int SaleID)
        {
            string host = _httpContext.HttpContext.Request.Host.Host.Replace("www", "pay").Replace("aiweb", "pay").Replace("webx", "pay").Replace("web.", "minipay.").Replace("yun4.", "pay.").Replace("p.", "t.");
#if DEBUG
            host = "pay.aiyard.cn";
#endif 
            string Url = (host.Contains("minipay.") ? "https://" : "http://") + host + ":1888/api/v1.0/YardLogin/GetNormalUrl?host=https%3A%2F%2F" + host + "%2F&pageName=barcode&StationId=" + Station_ID.ToString() + "&SaleId=" + SaleID.ToString() + "&BillNo=";

            return _httpService.Get(Url).Replace('"', ' ').Trim();
        }
        #endregion

        #region 获取小程序码
        /// <summary>
        /// 获取小程序码
        /// </summary>
        /// <param name="Station_ID"></param>
        /// <param name="SaleID"></param>
        /// <returns></returns>
        public string GetBarCode_Mini(int Station_ID, int SaleID, int width, string env_version, string color, bool is_hyaline)
        {
            bool check_path = false;
            if (env_version == "release") { check_path = true; }
            bool auto_color = false;
            string miniParams = "&check_path="+ check_path.ToString() + "&env_version="+ env_version + "&width="+ width + "&auto_color="+ auto_color.ToString() + "&color=" + color + "&is_hyaline=" + is_hyaline.ToString();
            string host = _httpContext.HttpContext.Request.Host.Host.Replace("www", "pay").Replace("aiweb", "pay").Replace("webx", "pay").Replace("web.", "minipay.").Replace("yun4.", "pay.").Replace("p.", "t.");
#if DEBUG
            host = "pay.aiyard.cn";
#endif

            string Url = (host.Contains("minipay.") ? "https://" : "http://") + host + ":1888/api/v1.0/YardLogin/GetSaleUrl_Mini?host=pages/index/index&StationId=" + Station_ID.ToString() + "&SaleId=" + SaleID.ToString() + "&timestamp=1"+ miniParams;
            string fileName = _httpService.Get(Url).Replace('"', ' ').Trim();
            if (fileName.StartsWith("!"))
            {
                return fileName;
            }
            return (host.Contains("minipay.") ? "https://" : "http://") + host + ":1888/MiniCode/" + fileName;
        }
        #endregion

        #region 获取动态小程序码
        /// <summary>
        /// 获取动态小程序码
        /// </summary>
        /// <param name="Station_ID"></param>
        /// <param name="SaleID"></param>
        /// <returns></returns>
        public string GetDTBarCode_Mini(int Station_ID, int SaleID, int width, string env_version, string color, bool is_hyaline)
        {
            bool check_path = false;
            if (env_version == "release") { check_path = true; }
            bool auto_color = false;
            string miniParams = "&check_path=" + check_path.ToString() + "&env_version=" + env_version + "&width=" + width + "&auto_color=" + auto_color.ToString() + "&color=" + color + "&is_hyaline=" + is_hyaline.ToString(); 
            string host = _httpContext.HttpContext.Request.Host.Host.Replace("www", "pay").Replace("aiweb", "pay").Replace("webx", "pay").Replace("web.", "minipay.").Replace("yun4.", "pay.").Replace("p.", "t.");
#if DEBUG
            host = "pay.aiyard.cn";
#endif 
            string Url = (host.Contains("minipay.") ? "https://" : "http://") + host + ":1888/api/v1.0/YardLogin/GetNormalUrl_Mini?host=pages/index/index&pageName=barcode&StationId=" + Station_ID.ToString() + "&SaleId=" + SaleID.ToString() + "&BillNo="+ miniParams;

            string fileName = _httpService.Get(Url).Replace('"', ' ').Trim();
            if (fileName.StartsWith("!"))
            {
                return fileName;
            }
            return (host.Contains("minipay.") ? "https://" : "http://") + host + ":1888/MiniCode/" + fileName;
        }
        #endregion

         

    }
}


